import json
from oauth.models import *
from oauth.serializers import  UserProfileserializer

from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.throttling import AnonRateThrottle,UserRateThrottle
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken
from rest_framework_jwt.utils import jwt_decode_handler
from rest_framework_jwt.authentication import JSONWebTokenAuthentication  # jwt用户认证


from django.contrib.auth import get_user_model
Users = get_user_model()

from utils.custom_log   import log_start
logger = log_start('account')


class UserLoginView(ObtainJSONWebToken):
    """
    post:
    用户登录

    用户登录, status: 200(成功), return: Token信息
    """
    throttle_classes = [AnonRateThrottle,UserRateThrottle] # 限流
    
    def post(self, request, *args, **kwargs):
    
        # 重写父类方法, 定义响应字段内容
        response = super().post(request, *args, **kwargs)
        if response.status_code == 200:
          
            return response
        else:
            info = "{}".format(response.status_code)
            logger.error(info)
            if response.data.get('non_field_errors'):
                # 日后将增加用户多次登录错误,账户锁定功能(待完善)
                if isinstance(response.data.get('non_field_errors'), list) and len(
                        response.data.get('non_field_errors')) > 0:
                    if response.data.get('non_field_errors')[0].strip() == '无法使用提供的认证信息登录。':
                        return Response(data={'detail': '用户名或密码错误'}, status=status.HTTP_400_BAD_REQUEST)
            raise ValidationError(response.data)


class UserInfoView(APIView):
    """
    get:
    当前用户信息

    当前用户信息,status: 200(成功), return: 用户信息和权限
    """
    authentication_classes = [JSONWebTokenAuthentication]
    def get(self, request):
  
        token = request.META.get('HTTP_AUTHORIZATION')
        token_user = jwt_decode_handler(token.split()[1])
        user_id = token_user['user_id']  # 获取登陆用户id
        data = Users.objects.get(id=user_id).get_user_info()
        data["avatar"]= request._current_scheme_host + data['avatar']
        return Response(data=data)
        

class LogoutAPIView(APIView):
    """
    post:
    退出登录

    退出登录,status: 200 (成功), return: None
    """
    authentication_classes = [JSONWebTokenAuthentication]
    def post(self, request):
        content = {}
        # 后续将增加redis token黑名单功能
        return Response(data=content)

